//定义电影导演相关的接口
const express = require('express')
const router = express.Router()
const response = require('../pool/Response')
//引入mysql连接池
const pool = require('../pool/pool')


const joi = require('joi')

//新增导演列表
router.post('/movie-director/add',(req,res) => {
    let {directorName,directorAvatar} = req.body
    let schema = joi.object({
        directorName:joi.string().required(),
        directorAvatar:joi.string().required()
    })
    let {error,value} = schema.validate(req.body)
    if(error){
        res.send(response.error(400,error))
        return;
    }
    pool.query('insert into movie_director (director_name,director_avatar ) values(?,?)',[directorName,directorAvatar],(err,result)=>{
        if(err){
            res.send(response.error(500,err))
            throw err;
        }
        res.send(response.ok())
    })
})


//删除导演
router.post('/movie-director/del',(req,res) => {
    let {id} = req.body
    //表单验证
    let schema = joi.object({
        id:joi.string().required()
    })
    let {error,value} =schema.validate(req.body)
    if(error){
        res.send(response.error(400,error))
        return
    }
    pool.query('delete from movie_director where id = ?',[id],(error,result) => {
        if(error){
            res.send(response.error(500,error))
            throw error;
        }
        res.send(response.ok())
    })
})

//查询所有导演接口
router.get('/movie-directors',(req,res) => {
    let {page,pagesize} = req.query
    let schema = joi.object({
        page:joi.number().required(),
        pagesize:joi.number().integer().max(100).required()
    })
   let {error,value} = schema.validate(req.query)
    let star = (page-1) * 10
    let size = parseInt(pagesize)
    if(error){
        res.send(response.error(400,error))
        return;
    }
    pool.query('select * from movie_director limit ?,?',[star,size],(err,result)=>{
        if(err){
            throw err;
        }
        res.send(response.ok(result))
    })
})

 //搜索框查询 
router.post('/movie-directors/name',(req,res) => {
    let {name} = req.body
    let schema = joi.object({
        name:joi.string().required()
    })
    let {error,value} = schema.validate(req.body)
    if(error){
     res.send(response.error(400,error))
     return;
    }
    pool.query('select * from movie_director where director_name like ?',[`%${name}%`],(error,result) => {
        if(error){
            res.send(response.error(response.error(500,error)))
            throw error
        }
        res.send(response.ok(result))
    })
})

module.exports = router